package com.zrrd._01_servlet.servlet;

import com.zrrd._01_servlet.mapper.StudentMapper;
import com.zrrd._01_servlet.pojo.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @author WanJl
 * @version 1.0
 * @title StudentRegisterServlet
 * @description
 * @create 2024/1/15 9:34
 */
@WebServlet("/student/register")
public class StudentRegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //转码
        req.setCharacterEncoding("UTF-8");
        //获取前端的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String realName = req.getParameter("realName");
        Integer age = Integer.parseInt(req.getParameter("age"));
        String sex = req.getParameter("sex");
        //创建实体类对象Student，把这些从前端传递过来的属性参数，添加进Student对象的属性变量中
        Student student = new Student(null, username, password, realName, age, sex);
        //调用StudentMapper的register方法
        StudentMapper studentMapper = new StudentMapper();
        try {
            boolean register = studentMapper.register(student);
            if (register){
                //如果注册成功，那么响应重定向，跳转到登录页
                resp.sendRedirect("/JMS2301_WEB_war/login.html");
            }else {
                //失败，则跳转回注册页面
                resp.sendRedirect("/JMS2301_WEB_war/register.html");
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
